package com.estore.service;

import com.estore.model.OrderRecord;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

public class OrderService implements Serializable {
    private static final long serialVersionUID = 1L;

    private List<OrderRecord> orderRecords;
    private final String orderDataFile;
    private AtomicLong orderCounter;

    public OrderService() {
        this("orders.dat");
    }

    public OrderService(String orderDataFile) {
        this.orderDataFile = Objects.requireNonNull(orderDataFile, "Order data file cannot be null");
        this.orderRecords = new ArrayList<>();
        this.orderCounter = new AtomicLong(1);
        loadOrders();
    }

    public void addOrder(OrderRecord order) {
        orderRecords.add(Objects.requireNonNull(order, "Order cannot be null"));
        saveOrders();
    }

    public List<OrderRecord> getAllOrders() {
        return new ArrayList<>(orderRecords);
    }

    public String generateOrderId() {
        return "ORD" + String.format("%06d", orderCounter.getAndIncrement());
    }

    @SuppressWarnings("unchecked")
    private void loadOrders() {
        Path path = Paths.get(orderDataFile);
        if (!Files.exists(path)) {
            System.out.println("订单数据文件不存在，将创建新文件: " + orderDataFile);
            return;
        }

        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(orderDataFile))) {
            Object obj = in.readObject();
            if (obj instanceof List) {
                this.orderRecords = (List<OrderRecord>) obj;
            }

            // 从现有订单中找出最大的序号，避免重复
            long maxId = 0;
            for (OrderRecord order : orderRecords) {
                try {
                    String orderId = order.getOrderId();
                    if (orderId.startsWith("ORD")) {
                        long idNum = Long.parseLong(orderId.substring(3));
                        maxId = Math.max(maxId, idNum);
                    }
                } catch (NumberFormatException e) {
                    // 忽略解析失败的情况
                }
            }
            this.orderCounter.set(maxId + 1);

            System.out.println("订单数据加载成功！加载了 " + orderRecords.size() + " 个订单");
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("订单数据加载失败: " + e.getMessage());
            this.orderRecords = new ArrayList<>();
        }
    }

    private void saveOrders() {
        try {
            Path path = Paths.get(orderDataFile);
            Path parentDir = path.getParent();
            if (parentDir != null) {
                Files.createDirectories(parentDir);
            }

            try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(orderDataFile))) {
                out.writeObject(orderRecords);
                System.out.println("订单数据保存成功！文件路径: " + orderDataFile);
            }
        } catch (IOException e) {
            System.err.println("订单数据保存失败: " + e.getMessage());
        }
    }
}
